package com.ybdz.scanner.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.qmuiteam.qmui.widget.QMUIEmptyView;
import com.ybdz.scanner.R;
import com.ybdz.scanner.adapter.LookTakeAdapter;
import com.ybdz.scanner.api.ApiStore;
import com.ybdz.scanner.api.Constant;
import com.ybdz.scanner.base.BaseActivity;
import com.ybdz.scanner.bean.TakeInventoryBean;
import com.ybdz.scanner.bean.TakeTablesBean;
import com.ybdz.scanner.event.ObjEvent;
import com.ybdz.scanner.receiver.ScannerInterface;
import com.ybdz.scanner.utils.MyApplication;
import com.ybdz.scanner.utils.MyToast;
import com.ybdz.scanner.utils.UIUtils;
import com.ybdz.scanner.view.FullyLinearLayoutManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @ClassName: LookTakeActivity
 * @author: zhao
 * @Description: 出库单
 * @date 2018/2/24 17:00
 */
public class LookTakeActivity extends BaseActivity {

    @BindView(R.id.rv)
    RecyclerView mRv;
    @BindView(R.id.tv_id)
    TextView mTvId;
    @BindView(R.id.ll_head)
    LinearLayout mLlHead;
    @BindView(R.id.empty)
    QMUIEmptyView mEmpty;
    @BindView(R.id.top_hint)
    LinearLayout mTopHint;

    private TakeItemResultReceiver mResultReceiver;
    private ScannerInterface mScanner;
    private boolean isContinue = false;        //连续扫描的标志
    private LookTakeAdapter mAdapter;
    private String outFormId;
    private String id;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_look_take);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        mResultReceiver = new TakeItemResultReceiver();
        mScanner = initScanner(mResultReceiver);
        mEmpty.show(true);
        initRecycleView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        showLoading();
        initData(id);
    }

    private void tryHttp() {
        mEmpty.show(false, "服务器繁忙，请稍后再试", null, "点击重试", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEmpty.show(true);
                initData(id);
            }
        });
    }

    /**
     * 出库单的网络请求
     *
     * @param id
     */
    private void initData(final String id) {
        ApiStore.takeTable(id).enqueue(new Callback<TakeTablesBean>() {
            @Override
            public void onResponse(Call<TakeTablesBean> call, Response<TakeTablesBean> response) {
                hideLoading();
                if (response.isSuccessful() && response.code() == 200 && response.body().getStatus() == 200) {
                    mEmpty.hide();
                    List<TakeTablesBean.DataBean> data = response.body().getData();
                    outFormId = data.get(0).getOutFormId();
                    selectRedTop(data);
                    mAdapter.setData(data);
                    mTvId.setText(id);
                    mAdapter.notifyDataSetChanged();
                    mLlHead.setVisibility(View.VISIBLE);
                } else {
                    tryHttp();
                }
            }

            @Override
            public void onFailure(Call<TakeTablesBean> call, Throwable t) {
                hideLoading();
                tryHttp();
            }
        });
    }


    /**
     * 判断该出库单是否为未完成状态
     *
     * @param data
     */
    private void selectRedTop(List<TakeTablesBean.DataBean> data) {
        int count = 0;
        for (int i = 0; i < data.size(); i++) {
            Integer scanQuantity = data.get(i).getScanQuantity();
            Integer quantity = data.get(i).getQuantity();
            if (scanQuantity.intValue() == quantity.intValue() && scanQuantity !=null && quantity != null) {
                count++;
            }
            if (count == data.size()){
                //逻辑没写完
                mTopHint.setVisibility(View.GONE);
                //onFail("该出库单已经出库完成");
            }else {
                mTopHint.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * 初始化recycleview
     */
    private void initRecycleView() {
        FullyLinearLayoutManager linearLayoutManager = new FullyLinearLayoutManager(this);
        mRv.setNestedScrollingEnabled(false);
        mRv.setLayoutManager(linearLayoutManager);
        mAdapter = new LookTakeAdapter();
        mRv.setAdapter(mAdapter);
    }

    @OnClick({R.id.back, R.id.home, R.id.bt_scan, R.id.bt_history})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:                     //返回
                finish();
                break;
            case R.id.home:                     //返回首页
                startActivity(new Intent(LookTakeActivity.this, MainActivity.class));
                finish();
                break;
            case R.id.bt_scan:                  //开启扫描
                MyApplication.setScannerClick(Constant.Take_item);
                mScanner.scan_start();
                break;
            case R.id.bt_history:               //查看历史操作
                //startActivity(new Intent(LookTakeActivity.this,TakeHistoryActivity.class));
                break;
        }
    }

    /**
     * 接收EventBus传递的数据
     *
     * @param onResponeEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void getOutFormId(ObjEvent onResponeEvent) {
        if (onResponeEvent.getId().equals("formId")) {
            id = (String) onResponeEvent.getObj();
        }
    }


    /**
     * 指定139的物理按键（中间黄色按键）按下来出发扫描
     */
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == 139 && event.getRepeatCount() == 0) {
            mScanner.scan_start();
            MyApplication.setScannerClick("TAKE_ITEM");
        }
        return super.onKeyDown(keyCode, event);
    }

    public boolean onKeyUp(int keyCode, KeyEvent event) {   //按键弹起，停止扫描
        if (keyCode == 139) {
            mScanner.scan_stop();
        } else if (keyCode == 140) {
            mScanner.scan_stop();

            isContinue = !isContinue;
            if (isContinue) {
                mScanner.continceScan(true);
            } else {
                mScanner.continceScan(false);
            }
        }
        return super.onKeyUp(keyCode, event);
    }


    /**
     * 利用广播接收扫描结果
     */
    private class TakeItemResultReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            final String scanResult = intent.getStringExtra("value");
            //如果条码长度大于0，解码成功。如果解码长度等于0，解码失败。
            if (intent.getAction().equals(Constant.RES_ACTION)) {
                //获取扫描结果
                if (scanResult.length() > 0 && MyApplication.getScannerClick().equals(Constant.Take_item)) {
                    //解码成功
                    if (scanResult.contains(Constant.Ininventoryitem)) {
                        String[] split = scanResult.split(Constant.Sprit);
                        if (split[split.length - 2].equals(Constant.Ininventoryitem)) {
                            String result = split[split.length - 1];
                            getOut(result);
                        } else {
                            MyToast.show(UIUtils.getContext(), "未查询到产品信息，请重新扫码。");
                        }
                    } else {
                        MyToast.show(UIUtils.getContext(), "未查询到产品信息，请重新扫码。");
                    }

                } else {
                    //扫码失败
                }
            }
        }
    }

    /**
     * 扫描单品的网络请求
     *
     * @param result
     */
    private void getOut(String result) {
        showLoading();
        ApiStore.getTake(result, outFormId).enqueue(new Callback<TakeInventoryBean>() {
            @Override
            public void onResponse(Call<TakeInventoryBean> call, Response<TakeInventoryBean> response) {
                if (response != null && response.isSuccessful()) {
                    hideLoading();
                    if (response.body().getData() != null) {
                        int status = response.body().getData().getStatus();
                        switch (status) {
                            case 100:   //正常状态
                                TakeInventoryBean.DataBean data = response.body().getData();
                                EventBus.getDefault().postSticky(data);
                                startActivity(new Intent(LookTakeActivity.this, NormalProductActivity.class));
                                break;
                            case 101:   //产品已出库完成,不能出库
                                onFail("出库已完成,不能出库");
                                break;
                            case 102:   //该产品不是应出批次
                                startActivity(new Intent(LookTakeActivity.this, ErrorProductActivity.class));
                                break;
                            case 103:   //该产品已出库
                                startActivity(new Intent(LookTakeActivity.this, EndProductActivity.class));
                                break;
                            default:
                                MyToast.show(LookTakeActivity.this, "未查询到产品信息，请重新扫码。");
                                break;
                        }
                    } else {
                        hideLoading();
                        onFail("查询失败");
                    }
                } else {
                    hideLoading();
                    MyToast.show(LookTakeActivity.this, "未查询到产品信息，请重新扫码。");
                }
            }

            @Override
            public void onFailure(Call<TakeInventoryBean> call, Throwable t) {
                hideLoading();
                onFailTimeOut();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        finishScanner(mResultReceiver);
    }
}
